package com.lz.sports.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Region
import android.util.AttributeSet
import android.view.View
import com.lz.sports.R

class ClipShadeView : View {
    //半径, 中心坐标点
    private var radio = 0f
    private var centerX = 0f
    private var centerY = 0f

    //圆宽度
    private var shadeWidth = 0

    //画的区域
    private val path = Path()
    private val paint = Paint()

    //阴影颜色
    private var shadeColor = Color.WHITE

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClipShadeView)
            shadeColor = typedArray.getColor(R.styleable.ClipShadeView_shadeColor, shadeColor)
            typedArray.recycle()
        }

        setLayerType(LAYER_TYPE_SOFTWARE, null)
        paint.color = shadeColor
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 1f
        paint.isAntiAlias = true
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        shadeWidth = width - paddingLeft - paddingRight
        radio = shadeWidth / 2.0f
        centerX = radio + paddingLeft
        centerY = radio + paddingTop

        path.addCircle(centerX, centerY, radio, Path.Direction.CCW);
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (shadeWidth <= 0) return
        canvas.save()
        canvas.clipPath(path, Region.Op.DIFFERENCE)
        canvas.drawColor(shadeColor)
        canvas.restore()
        canvas.drawCircle(centerX, centerY, radio, paint)
    }
}